import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { useState, useEffect } from 'react';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import {post} from "../../service";

function App({ defaultValue, onChange }) {
    const [editor, setEditor] = useState(null);
    const [html, setHtml] = useState(defaultValue || null);

    // Toolbar 配置
    const toolbarConfig = {
        excludeKeys: ['emoticon', 'video'], // 排除菜单
    };

    // Editor 配置
    const editorConfig = {
        placeholder: '请输入内容...',
        MENU_CONF: {
            uploadImage: {
                // 自定义图片上传
                async customUpload(file, insertFn) {
                    const form = new FormData();
                    form.append('file', file);
                    try {
                        const response = await post('/api/upload', form);
                        const { file: uploadedFile } = response;
                        insertFn(uploadedFile.url); // 插入图片
                    } catch (error) {
                        console.error('Image upload failed:', error);
                    }
                },
            },
        },
        onChange(editorInstance) {
            console.log(editorInstance)
            const htmlContent = editorInstance.getHtml();
            setHtml(htmlContent);
            if (onChange) {
                onChange(htmlContent);
            }
        },
    };

    // 销毁 editor 实例
    useEffect(() => {
        return () => {
            if (editor) {
                editor.destroy();
                setEditor(null);
            }
        };
    }, [editor]);

    return (
        <>
            <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
                <Toolbar
                    editor={editor}
                    defaultConfig={toolbarConfig}
                    mode="default"
                    style={{ borderBottom: '1px solid #ccc' }}
                />
                <Editor
                    defaultConfig={editorConfig}
                    value={html}
                    onCreated={setEditor}
                    mode="default"
                    style={{ height: '300px', overflowY: 'hidden' }}
                />
            </div>
        </>
    );
}

export default App;
